import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import './index.css'
import { useNavigate , useLocation , useParams} from 'react-router-dom'

let mynative
let mylocation
let myparam
async function Athurize (userid , userpwd){
    console.log(`userid=${userid}userpwd=${userpwd}`)
            // console.log(myparam)
            let msg = {
                login_state:false , msg:""
            }
            let skipurl = "/login"
            try{
                let response = await fetch(`/device/userlogin?userid=${userid}&userpwd=${userpwd}` , {
                    method: 'GET',
                }).then(data => data.json())
                .then(result =>{
                   return result
                })
                if(response===1) {
                    msg.login_state = true
                    msg.msg = "登陆成功"
                    skipurl = '/main'
                    
                } else {
                    msg.msg = "账号或者密码错误"
                }
            } catch {
               
               msg.msg = "-_-! 。。。。发生未知错误，请检查网络!"
            }
            PubSub.publish("login" , msg)
            mynative(skipurl+`/${userid}/${userpwd}`, {replace: false })
}

function LoginError(args) {
    const {msg} = {...args}

    return (
        <div style={{color:"red"}}>
            {msg}
        </div>
    )
}

function LoginButton(args){
    const {userid , userpwd} = {...args}
    mynative = useNavigate()
    mylocation = useLocation()
    myparam = useParams()
    return (
        <button onClick={(event)=>{Athurize(userid , userpwd)}}>Login</button>
    )
}

export default class Logininput extends Component {
    state = {
        userid:"",
        userpwd:""
    }
    render() {
        return (
            <div className='userLogin'>
                <input onChange={(event)=>{this.setState({userid : event.target.value})}} type="text" />
                <input onChange={(event)=>{this.setState({userpwd : event.target.value})}} type="password" />
                <LoginButton {...this.state}/>
                <LoginError {...this.props}/>
            </div>
        )
    }
}

